var icdev = 0; //设备句柄
var lock = new Lock()
var data = undefined
var resetData = undefined
var uid = undefined
var msg = {} ;
var layer = layui.layer
var form = layui.form
var status = 0 // 0 未复位   1 已复位
var reader = getReader(async function(){
    // 连接USB读卡器
    try {
        reader.connectUsb(); //连接usb设备
        await lock.wait()
    } catch (e) {
        msg.value = msg.value + e.Message + "\n";
    }
}); //获取reader对象, getReader会自动连接ReaderService服务
if (reader == null) {
    alert('您的浏览器不支持读写器服务.');
}

// 设置回调
reader.onResult(function (ret) {
    data = ret
    console.log("返回："+data.resultData)
    lock.notify(data)
    //执行成功
    if (ret.result == 0) {
        switch (ret.functionId) {
            case READER_CMD._reader_server_connect:
                break;
            case READER_CMD._reader_cmd_connect:
                icdev = parseInt(ret.resultData); //连接成功后, resultData 为设备句柄
                msg.value = msg.value + "读写器连接成功.\n";
                break;
            case READER_CMD._reader_cmd_disconnect:
                msg.value = msg.value + "读写器断开连接成功.\n";
                break;
            case READER_CMD._reader_cmd_beep:
                msg.value = msg.value + "读写器鸣响成功.\n";
                break;
            case READER_CMD._reader_cmd_rf_card:
            case READER_CMD._reader_cmd_rf_card_b:
                msg.value = msg.value + "寻卡成功, 卡片序列号: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_c_cpu_reset:
                msg.value = msg.value + "非接触式 TypeA CPU 卡复位成功. 复位信息: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_c_cpu_reset_b:
                msg.value = msg.value + "非接触式 TypeB CPU 卡复位成功.\n";
                break;
            case READER_CMD._reader_cmd_rf_halt:
            case READER_CMD._reader_cmd_rf_halt_b:
                msg.value = msg.value + "终止卡片操作成功.\n";
                break;
            case READER_CMD._reader_cmd_uc_auth_key:
                msg.value = msg.value + "Ultralight C 校验密码成功.\n";
                break;
            case READER_CMD._reader_cmd_uev_auth_key:
                msg.value = msg.value + "Ultralight EV 校验密码成功.\n";
                break;
            case READER_CMD._reader_cmd_u_read:
                msg.value = msg.value + "Ultralight / Ultralight C 读数据成功. 读取到的数据: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_u_write:
                msg.value = msg.value + "Ultralight / Ultralight C 写数据成功.\n";
                break;
            case READER_CMD._reader_cmd_uc_change_key:
                msg.value = msg.value + "更改  Ultralight C 密码成功.\n";
                break;
        }
    } else {
        //失败打印错误信息
        msg.value = msg.value + ret.resultData + "\n";
    }
    // console.log(data)
});


// 定时寻卡
async function find_card(){
    try {
        reader.rfCard(icdev, 1);
        await lock.wait()
        uid = data.resultData
        console.log(uid)
        if(uid != "请求失败。" && uid != "设备未连接。"){
            clearInterval(timer)
            status = 1
            cardNo = uid
            $("input[name='cardNo']").val(uid)
            form.render()
        }
        reader.mifareCpuReset(icdev);
        await lock.wait()
        resetData = data.resultData
    } catch (e) {
        console.log(e)
        // msg.value = msg.value + e.Message + "\n";
    }
}

timer = setInterval(find_card , 1000)

async function write(){
    if(status == 1) {
        layer.confirm("确认开卡?,在开卡过程中请勿将卡片拿开" , async function(){
            layer.load(1)
            // 1.查看目录是否存在
            reader.mifareCpuTransmit(icdev , "00A40000021001")
            await lock.wait()
            if(data.resultData != "6A82" && data.resultData != "6D00") {
                layer.closeAll()
                layer.msg("卡已被使用,无法重复写卡")
                return false
            }
            // 获取随机数
            var result = undefined
            reader.mifareCpuTransmit(icdev, "0084000004");
            await lock.wait() ;
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return false
            }
            //  测试
            // $.ajax({
            //     url:"/cpu_card/certification?cid="+uid+"&random="+data.resultData+"&type=0" ,
            //     async:false ,
            //     success:function(res){
            //         result = "0082000008" + res.data
            //     }
            // })
            // if(result == undefined) {
            //     layer.msg("网络异常,无法完成开卡")
            //     return
            // }
            // reader.mifareCpuTransmit(icdev , result) ;
            // await lock.wait()
            //
            // reader.mifareCpuTransmit(icdev, "0084000004") ;
            // await lock.wait() ;
            // if(checkRs() != undefined) {
            //     layer.closeAll()
            //     layer.msg(checkRs())
            //     return false
            // }
            //  测试

            // 请求开卡指令
            result = undefined
            $.ajax({
                url:"/cpu_card/create_card?cid="+uid+"&uid="+staff.id+"&ast="+resetData+"&random="+data.resultData ,
                async:false ,
                success:function(res) {
                    result = res
                }
            })
            if(result == undefined) {
                layer.closeAll()
                layer.msg("网络异常无法请求到开卡指令")
                return
            }else{
                if(result.code != 200) {
                    layer.closeAll()
                    layer.msg(result.msg)
                    return
                }else{
                    result = result.data
                }
            }

            // 测试
            // console.log(result)
            // 清除卡原本目录结构
            // reader.mifareCpuTransmit(icdev, result.clear_card);
            // await lock.wait() ;
            // if(checkRs() != undefined) {
            //     layer.msg(checkRs())
            //     return
            // }
            // 测试

            // 创建mf
            reader.mifareCpuTransmit(icdev, result.kaika);
            await lock.wait() ;
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            // 外部认证
            var wbrz = undefined
            reader.mifareCpuTransmit(icdev, "0084000004");
            await lock.wait() ;
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            $.ajax({
                url:"/cpu_card/certification?cid="+uid+"&random="+data.resultData+"&type=1" ,
                async:false ,
                success:function(res){
                    wbrz = "0082000008" + res.data
                }
            })
            if(result == undefined) {
                layer.closeAll()
                layer.msg("网络异常,无法完成开卡")
                return
            }
            reader.mifareCpuTransmit(icdev , wbrz) ;
            await lock.wait()
            // 设置根目录密钥
            reader.mifareCpuTransmit(icdev, result.root);
            await lock.wait()
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            // 创建文件夹
            await create_dir(result.create_dir)
            reader.mifareCpuTransmit(icdev, "00A40000021001");  // 进入目录
            await lock.wait()
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            // 目录外部认证
            reader.mifareCpuTransmit(icdev, "0084000004");
            await lock.wait() ;
            $.ajax({
                url:"/cpu_card/certification?cid="+uid+"&random="+data.resultData+"&type=2" ,
                async:false ,
                success:function(res){
                    wbrz = "0082000008" + res.data
                }
            })
            reader.mifareCpuTransmit(icdev , wbrz) ;
            await lock.wait()
            // 设置目录密钥
            reader.mifareCpuTransmit(icdev, result.dir);
            await lock.wait()
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            // 设置消费密钥
            reader.mifareCpuTransmit(icdev, result.xf);
            await lock.wait()
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            // 5.设置圈存密钥
            reader.mifareCpuTransmit(icdev, result.qc);
            await lock.wait()
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            // 6.设置TAC密钥
            reader.mifareCpuTransmit(icdev, result.tac);
            await lock.wait()
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            // 7.设置PIN密码
            reader.mifareCpuTransmit(icdev, result.pin);
            await lock.wait()
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            // 进入目录
            reader.mifareCpuTransmit(icdev, "00A40000021001");  // 进入目录
            await lock.wait()
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            // 目录外部认证
            reader.mifareCpuTransmit(icdev, "0084000004");
            await lock.wait() ;
            $.ajax({
                url:"/cpu_card/certification?cid="+uid+"&random="+data.resultData+"&type=2" ,
                async:false ,
                success:function(res){
                    wbrz = "0082000008" + res.data
                }
            })
            reader.mifareCpuTransmit(icdev , wbrz) ;
            await lock.wait()
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            for(var i in result.createFiles) {
                // 8.创建文件
                reader.mifareCpuTransmit(icdev , result.createFiles[i])
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
            }
            // 写文件
            reader.mifareCpuTransmit(icdev, result.select_file);
            await lock.wait()
            if(checkRs() != undefined) {
                layer.closeAll()
                layer.msg(checkRs())
                return
            }
            for(var i in result.write_file) {
                reader.mifareCpuTransmit(icdev , result.write_file[i])
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
            }

            layer.msg("开卡成功")
            reader.rfHalt(icdev);
            setTimeout(function(){
                layer.closeAll() ;
                parent.location.reload()
            } , 300)
        })
    }else{
        layer.msg("未识别到卡,请重新放置")
    }
}

// parent.location.reload()

// 创建目录
async function create_dir(str){
    try {
        // 进入根目录
        reader.mifareCpuTransmit(icdev, "00A40000023F00");
        await lock.wait()
        // 外部认证
        var wbrz = undefined
        reader.mifareCpuTransmit(icdev, "0084000004");
        await lock.wait() ;
        if(checkRs() != undefined) {
            layer.msg(checkRs())
            return
        }
        $.ajax({
            url:"/cpu_card/certification?cid="+uid+"&random="+data.resultData+"&type=1" ,
            async:false ,
            success:function(res){
                wbrz = "0082000008" + res.data
            }
        })
        if(wbrz == undefined) {
            layer.msg("网络异常,无法完成开卡")
            return
        }
        reader.mifareCpuTransmit(icdev , wbrz) ;
        await lock.wait()
        // 1.进入目录
        reader.mifareCpuTransmit(icdev, "00A40000021001");
        await lock.wait()
        if(data.resultData == "6A82") {
            // 建立目录
            reader.mifareCpuTransmit(icdev, str);
            await lock.wait()
        }
        // else{
        //     alert("目录已经存在")
        // }
    } catch (e) {
        msg.value = msg.value + e.Message + "\n";
    }
}


function checkRs(){
    switch(data.resultData) {
        case "6200":
            return "警告 信息未提供"
        case "6281":
            return "警告 回送数据可能"
        case "6282":
            return "警告 文件长度小于Le"
        case "6283" :
            return "警告 选中的文件无效"
        case "6284":
            return "警告 FCI格式与P2指定的不符"
        case "6300":
            return "警告 鉴别失败"
        case "63C2":
            return "警告 校验失败（允许重试次数2）"
        case "63C1":
            return "警告 校验失败（允许重试次数1）"
        case "6400":
            return "状态标志位没有变"
        case "6581":
            return "内存失败"
        case "6700":
            return "长度错误"
        case "6882" :
            return "不支持安全报文"
        case "6981":
            return "命令与文件结构不相容，当前文件非所需文件"
        case "6982":
            return "操作条件（AC）不满足，没有校验PIN"
        case "6983":
            return "您的卡已被锁定"
        case "6984":
            return "随机数无效，引用的数据无效"
        case "6985":
            return "使用条件不满足"
        case "6986":
            return "不满足命令执行条件（不允许的命令，INS有错）"
        case "6987":
            return "MAC丢失"
        case "6988":
            return "MAC不正确"
        case "698D":
            return "保留"
        case "6A80":
            return "数据域参数不正确"
        case "6A81":
            return "功能不支持；创建不允许；目录无效；应用锁定"
        case "6A82":
            return "该文件未找到"
        case "6A83":
            return "该记录未找到"
        case "6A84":
            return "文件预留空间不足"
        case "6A86":
            return "P1或P2不正确"
        case "6A88":
            return "引用数据未找到"
        case "6B00":
            return "参数错误"
        case "6C":
            return "Le长度错误"
        case "6E00":
            return "不支持的类：CLA有错"
        case "6F00":
            return "数据无效"
        case "6F01" :
            return "连接中断"
        case "6D00":
            return "不支持的指令代码"
        case "9301":
            return "您的卡余额不足"
        case "9302":
            return "MAC2错误"
        case "9303":
            return "应用被永久锁定"
        case "9401":
            return "您的卡余额不足"
        case "9402":
            return "交易计数器达到最大值"
        case "9403":
            return "密钥索引不支持"
        case "9406":
            return "所需MAC不可用"
        case "6900":
            return "不能处理"
        case "6901":
            return "命令不接受（无效状态）"
        case "61":
            return "正常 需发GET RESPONSE命令"
        case "6600":
            return  "接收通讯超时"
        case "6601":
            return "接收字符奇偶错"
        case "6602":
            return "校验和不对"
        case "6603":
            return "警告 当前DF文件无FCI"
        case "6604":
            return "警告 当前DF下无SF或KF"
        case "6E81":
            return "卡片已离开"
        default:
            return undefined
    }
}